package com.guomei.controller.curse;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.guomei.utils.PageData;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guomei.bean.User;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.domain.DistributeRecord;
import com.guomei.bean.curse.vo.CourseDistributionStats;
import com.guomei.bean.curse.vo.DistributeRecordDTO;
import com.guomei.bean.curse.vo.DistributeRecordVo;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.mapper.curse.DistributeRecordMapper;
import com.guomei.utils.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * 分销记录Controller
 */
@RestController
@RequestMapping("/api1/distributeRecord")
@Slf4j
public class DistributeRecordController {
    
    @Resource
    DistributeRecordMapper distributeRecordMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 查询分销记录
     */
    @PostMapping("/select")
    public Result<?> select(@RequestBody DistributeRecordDTO dto) {
        QueryWrapper<DistributeRecord> wrapper = new QueryWrapper<>();

        if (dto.getStudentId() != null) {
            wrapper.eq("student_id", dto.getStudentId());
        }

        if (dto.getDistributorId() != null) {
            wrapper.eq("distributor_id", dto.getDistributorId());
        }

        if (dto.getCourseId() != null) {
            wrapper.eq("course_id", dto.getCourseId());
        }

        if (dto.getOrderId() != null) {
            wrapper.eq("order_id", dto.getOrderId());
        }

        if (dto.getStatus() != null) {
            wrapper.eq("status", dto.getStatus());
        }

        if (dto.getSettleTimeStart() != null) {
            wrapper.ge("settle_time", dto.getSettleTimeStart());
        }

        if (dto.getSettleTimeEnd() != null) {
            wrapper.le("settle_time", dto.getSettleTimeEnd());
        }

        if (dto.getCreatedTimeStart() != null) {
            wrapper.ge("created_time", dto.getCreatedTimeStart());
        }

        if (dto.getCreatedTimeEnd() != null) {
            wrapper.le("created_time", dto.getCreatedTimeEnd());
        }

        if (dto.getIds() != null) {
            wrapper.in("id", dto.getIds());
        }

        List<DistributeRecord> items = distributeRecordMapper.selectList(wrapper);
        List<DistributeRecordVo> vos = new ArrayList<>();
        List<Long> courseIds = new ArrayList<>();
        List<Long> studentIds = new ArrayList<>();
        List<Long> distributorIds = new ArrayList<>();
        
        for (DistributeRecord item : items) {
            DistributeRecordVo vo = new DistributeRecordVo();
            vo.setId(item.getId());
            vo.setStudentId(item.getStudentId());
            vo.setDistributorId(item.getDistributorId());
            vo.setCourseId(item.getCourseId());
            vo.setOrderId(item.getOrderId());
            vo.setActualPayAmount(item.getActualPayAmount());
            vo.setDistributionRatio(item.getDistributionRatio());
            vo.setDistributeAmount(item.getDistributeAmount());
            vo.setStatus(item.getStatus());
            vo.setSettleTime(item.getSettleTime());
            vo.setRemark(item.getRemark());
            vo.setCreatedTime(item.getCreatedTime());
            vo.setUpdatedTime(item.getUpdatedTime());
            
            courseIds.add(item.getCourseId());
            studentIds.add(item.getStudentId());
            distributorIds.add(item.getDistributorId());
            vos.add(vo);
        }

        // 查询课程信息
        List<Course> courses = new ArrayList<>();
        if (!courseIds.isEmpty()) {
            courses = courseMapper.selectByIds(courseIds);
        }
        java.util.Map<Long, Course> courseById = new java.util.HashMap<>();
        for (Course c : courses) {
            if (c != null && c.getId() != null) {
                courseById.put(c.getId(), c);
            }
        }

        // 查询用户信息（学生和招生老师）
        List<User> users = new ArrayList<>();
        if (!studentIds.isEmpty()) {
            users.addAll(userMapper.selectByAll(studentIds));
        }
        if (!distributorIds.isEmpty()) {
            users.addAll(userMapper.selectByAll(distributorIds));
        }
        java.util.Map<Long, User> userById = new java.util.HashMap<>();
        for (User u : users) {
            if (u != null && u.getId() != null) {
                userById.put(u.getId(), u);
            }
        }

        // 设置关联信息
        for (DistributeRecordVo vo : vos) {
            vo.setCourse(courseById.get(vo.getCourseId()));
            vo.setStudent(userById.get(vo.getStudentId()));
            vo.setDistributor(userById.get(vo.getDistributorId()));
        }

        PageData<DistributeRecordVo> data = new PageData<>();
        data.setData(vos);
        data.setTotal((long) items.size());
        data.setPageNum(dto.getPageNum());
        data.setPageSize(dto.getPageSize());

        return Result.success(data);
    }

    /**
     * 保存分销记录
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody DistributeRecord record) {
        if (record.getId() != null) {
            // 更新
            distributeRecordMapper.updateById(record);
            return Result.success(record);
        }

        distributeRecordMapper.insert(record);
        return Result.success(record);
    }

    /**
     * 批量删除分销记录
     */
    @DeleteMapping("/dropByIds")
    public Result<?> dropByIds(@RequestBody List<Long> ids) {
        distributeRecordMapper.deleteBatchIds(ids);
        return Result.success();
    }

    /**
     * 根据招生老师ID查询分销记录
     */
    @PostMapping("/selectByDistributorId")
    public Result<?> selectByDistributorId(@RequestBody DistributeRecordDTO dto) {
        List<DistributeRecord> items = distributeRecordMapper.selectByDistributorId(dto.getDistributorId());
        return Result.success(items);
    }

    /**
     * 根据招生老师ID和状态查询分销记录
     */
    @PostMapping("/selectByDistributorIdAndStatus")
    public Result<?> selectByDistributorIdAndStatus(@RequestBody DistributeRecordDTO dto) {
        List<DistributeRecord> items = distributeRecordMapper.selectByDistributorIdAndStatus(
            dto.getDistributorId(), dto.getStatus());
        return Result.success(items);
    }

    /**
     * 统计招生老师的总分销金额
     */
    @PostMapping("/sumDistributeAmountByDistributorId")
    public Result<?> sumDistributeAmountByDistributorId(@RequestBody DistributeRecordDTO dto) {
        BigDecimal totalAmount = distributeRecordMapper.sumDistributeAmountByDistributorId(dto.getDistributorId());
        return Result.success(totalAmount != null ? totalAmount : BigDecimal.ZERO);
    }

    /**
     * 统计招生老师的总分销金额（按状态）
     */
    @PostMapping("/sumDistributeAmountByDistributorIdAndStatus")
    public Result<?> sumDistributeAmountByDistributorIdAndStatus(@RequestBody DistributeRecordDTO dto) {
        BigDecimal totalAmount = distributeRecordMapper.sumDistributeAmountByDistributorIdAndStatus(
            dto.getDistributorId(), dto.getStatus());
        return Result.success(totalAmount != null ? totalAmount : BigDecimal.ZERO);
    }

    /**
     * 统计课程的总分销金额
     */
    @PostMapping("/sumDistributeAmountByCourseId")
    public Result<?> sumDistributeAmountByCourseId(@RequestBody DistributeRecordDTO dto) {
        BigDecimal totalAmount = distributeRecordMapper.sumDistributeAmountByCourseId(dto.getCourseId());
        return Result.success(totalAmount != null ? totalAmount : BigDecimal.ZERO);
    }

    /**
     * 以课程为主表统计分销数据
     * 包含：分销金额、订单数量、招生老师数量
     */
    @PostMapping("/selectCourseDistributionStats")
    public Result<?> selectCourseDistributionStats(@RequestBody DistributeRecordDTO dto) {
        CourseDistributionStats stats = distributeRecordMapper.selectCourseDistributionStats(dto.getCourseId());
        
        // 如果没有查询到统计数据，则查询课程信息并初始化统计数据为0
        if (stats == null) {
            Course course = courseMapper.selectById(dto.getCourseId());
            if (course != null) {
                stats = new CourseDistributionStats();
                stats.setCourseId(course.getId());
                stats.setCourseName(course.getCourseName());
                stats.setTotalDistributeAmount(BigDecimal.ZERO);
                stats.setTotalOrders(0L);
                stats.setDistributorCount(0L);
                stats.setSettledDistributeAmount(BigDecimal.ZERO);
                stats.setPendingDistributeAmount(BigDecimal.ZERO);
                stats.setCancelledDistributeAmount(BigDecimal.ZERO);
                stats.setSettledOrders(0L);
                stats.setPendingOrders(0L);
                stats.setCancelledOrders(0L);
            }
        } else {
            // 确保所有金额字段不为null，如果为null则设置为0
            if (stats.getTotalDistributeAmount() == null) {
                stats.setTotalDistributeAmount(BigDecimal.ZERO);
            }
            if (stats.getSettledDistributeAmount() == null) {
                stats.setSettledDistributeAmount(BigDecimal.ZERO);
            }
            if (stats.getPendingDistributeAmount() == null) {
                stats.setPendingDistributeAmount(BigDecimal.ZERO);
            }
            if (stats.getCancelledDistributeAmount() == null) {
                stats.setCancelledDistributeAmount(BigDecimal.ZERO);
            }
            // 确保所有计数字段不为null，如果为null则设置为0
            if (stats.getTotalOrders() == null) {
                stats.setTotalOrders(0L);
            }
            if (stats.getDistributorCount() == null) {
                stats.setDistributorCount(0L);
            }
            if (stats.getSettledOrders() == null) {
                stats.setSettledOrders(0L);
            }
            if (stats.getPendingOrders() == null) {
                stats.setPendingOrders(0L);
            }
            if (stats.getCancelledOrders() == null) {
                stats.setCancelledOrders(0L);
            }
        }
        
        return Result.success(stats);
    }
}
